package org.example.leetcode.common.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;

import java.util.HashMap;
import java.util.Map;

public class TokenUtils {
    private static final String key="zhc";
    private static final String refresh_key="refresh_zhc";

    public static final int TOKEN_VALID_TIME=60*60*12;
    public static String createToken(Long id,String phone)
    {
        DateTime dateTime=DateTime.now();
        DateTime expireTime=dateTime.offsetNew(DateField.SECOND,TOKEN_VALID_TIME);
        Map<String,Object> payload=new HashMap<>();
        payload.put(JWTPayload.ISSUED_AT,dateTime);
        payload.put(JWTPayload.EXPIRES_AT,expireTime);
        payload.put(JWTPayload.NOT_BEFORE,dateTime);
        payload.put("id",id+"");
        payload.put("phone",phone);
        String token = JWTUtil.createToken(payload, key.getBytes());
        return token;
    }
    public static String createRefreshToken(Long id,String phone)
    {
        DateTime dateTime=DateTime.now();
        DateTime expireTime=dateTime.offsetNew(DateField.SECOND,TOKEN_VALID_TIME*7);
        Map<String,Object> payload=new HashMap<>();
        payload.put(JWTPayload.ISSUED_AT,dateTime);
        payload.put(JWTPayload.EXPIRES_AT,expireTime);
        payload.put(JWTPayload.NOT_BEFORE,dateTime);
        payload.put("id",id+"");
        payload.put("phone",phone);
        String token = JWTUtil.createToken(payload, refresh_key.getBytes());
        return token;
    }
    public static boolean validToken(String token)
    {
        return JWTUtil.verify(token,key.getBytes());
    }
    public static cn.hutool.json.JSONObject getJsonObjectFromToken(String token)
    {
        JWT jwt = JWTUtil.parseToken(token).setKey(key.getBytes());
        cn.hutool.json.JSONObject payloads = jwt.getPayloads();
        return payloads;
    }

}
